from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from django.core.exceptions import ValidationError

from .models import Flower, FlowerCategory
from .serializers import (
    FlowerListSerializer, FlowerDetailSerializer, FlowerCreateUpdateSerializer,
    FlowerCategorySerializer, ImageUploadSerializer
)
from .services import FlowerService, FlowerCategoryService, ImageUploadService, FlowerSearchService
from common.utils.response import APIResponse


class FlowerCategoryViewSet(viewsets.ModelViewSet):
    """鲜花分类视图集"""
    queryset = FlowerCategory.objects.all()
    serializer_class = FlowerCategorySerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = ['is_active']
    ordering_fields = ['sort_order', 'created_at']
    ordering = ['sort_order', '-created_at']

    def list(self, request, *args, **kwargs):
        """获取分类列表"""
        try:
            categories = FlowerCategoryService.get_active_categories()
            serializer = self.get_serializer(categories, many=True)
            return APIResponse.success(data=serializer.data, message="获取分类列表成功")
        except Exception as e:
            return APIResponse.error(message=f"获取分类列表失败: {str(e)}")

    def create(self, request, *args, **kwargs):
        """创建分类"""
        try:
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid():
                category = FlowerCategoryService.create_category(serializer.validated_data)
                return APIResponse.success(
                    data=FlowerCategorySerializer(category).data,
                    message="创建分类成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except Exception as e:
            return APIResponse.error(message=f"创建分类失败: {str(e)}")

    def update(self, request, *args, **kwargs):
        """更新分类"""
        try:
            serializer = self.get_serializer(data=request.data, partial=True)
            if serializer.is_valid():
                category = FlowerCategoryService.update_category(
                    kwargs['pk'], serializer.validated_data
                )
                return APIResponse.success(
                    data=FlowerCategorySerializer(category).data,
                    message="更新分类成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except Exception as e:
            return APIResponse.error(message=f"更新分类失败: {str(e)}")

    def destroy(self, request, *args, **kwargs):
        """删除分类"""
        try:
            FlowerCategoryService.delete_category(kwargs['pk'])
            return APIResponse.success(message="删除分类成功")
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"删除分类失败: {str(e)}")


class FlowerViewSet(viewsets.ModelViewSet):
    """鲜花商品视图集"""
    queryset = Flower.objects.all()
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['category', 'status', 'is_featured']
    search_fields = ['name', 'description']
    ordering_fields = ['price', 'sales_count', 'created_at', 'sort_order']
    ordering = ['sort_order', '-created_at']

    def get_serializer_class(self):
        if self.action == 'list':
            return FlowerListSerializer
        elif self.action in ['create', 'update', 'partial_update']:
            return FlowerCreateUpdateSerializer
        return FlowerDetailSerializer

    def list(self, request, *args, **kwargs):
        """获取鲜花列表"""
        try:
            filters = {
                'category_id': request.query_params.get('category_id'),
                'status': request.query_params.get('status'),
                'is_featured': request.query_params.get('is_featured'),
                'search': request.query_params.get('search'),
                'price_min': request.query_params.get('price_min'),
                'price_max': request.query_params.get('price_max'),
            }
            # 移除空值
            filters = {k: v for k, v in filters.items() if v is not None and v != ''}
            
            ordering = request.query_params.get('ordering')
            flowers = FlowerService.get_flower_list(filters, ordering)
            
            # 分页
            page = self.paginate_queryset(flowers)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
            
            serializer = self.get_serializer(flowers, many=True)
            return APIResponse.success(data=serializer.data, message="获取鲜花列表成功")
        except Exception as e:
            return APIResponse.error(message=f"获取鲜花列表失败: {str(e)}")

    def retrieve(self, request, *args, **kwargs):
        """获取鲜花详情"""
        try:
            flower = FlowerService.get_flower_detail(kwargs['pk'])
            serializer = self.get_serializer(flower)
            return APIResponse.success(data=serializer.data, message="获取鲜花详情成功")
        except Flower.DoesNotExist:
            return APIResponse.not_found(message="鲜花不存在")
        except Exception as e:
            return APIResponse.error(message=f"获取鲜花详情失败: {str(e)}")

    def create(self, request, *args, **kwargs):
        """创建鲜花"""
        try:
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid():
                flower = FlowerService.create_flower(serializer.validated_data)
                return APIResponse.success(
                    data=FlowerDetailSerializer(flower).data,
                    message="创建鲜花成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except Exception as e:
            return APIResponse.error(message=f"创建鲜花失败: {str(e)}")

    def update(self, request, *args, **kwargs):
        """更新鲜花"""
        try:
            serializer = self.get_serializer(data=request.data, partial=True)
            if serializer.is_valid():
                flower = FlowerService.update_flower(kwargs['pk'], serializer.validated_data)
                return APIResponse.success(
                    data=FlowerDetailSerializer(flower).data,
                    message="更新鲜花成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except Flower.DoesNotExist:
            return APIResponse.not_found(message="鲜花不存在")
        except Exception as e:
            return APIResponse.error(message=f"更新鲜花失败: {str(e)}")

    def destroy(self, request, *args, **kwargs):
        """删除鲜花"""
        try:
            FlowerService.delete_flower(kwargs['pk'])
            return APIResponse.success(message="删除鲜花成功")
        except Flower.DoesNotExist:
            return APIResponse.not_found(message="鲜花不存在")
        except Exception as e:
            return APIResponse.error(message=f"删除鲜花失败: {str(e)}")

    @action(detail=False, methods=['get'])
    def search(self, request):
        """搜索鲜花"""
        try:
            keyword = request.query_params.get('keyword', '')
            filters = {
                'category_id': request.query_params.get('category_id'),
                'price_min': request.query_params.get('price_min'),
                'price_max': request.query_params.get('price_max'),
            }
            filters = {k: v for k, v in filters.items() if v is not None and v != ''}
            
            flowers = FlowerSearchService.search_flowers(keyword, filters)
            
            # 分页
            page = self.paginate_queryset(flowers)
            if page is not None:
                serializer = FlowerListSerializer(page, many=True)
                return self.get_paginated_response(serializer.data)
            
            serializer = FlowerListSerializer(flowers, many=True)
            return APIResponse.success(data=serializer.data, message="搜索成功")
        except Exception as e:
            return APIResponse.error(message=f"搜索失败: {str(e)}")

    @action(detail=False, methods=['get'])
    def hot(self, request):
        """获取热门鲜花"""
        try:
            limit = int(request.query_params.get('limit', 10))
            flowers = FlowerSearchService.get_hot_flowers(limit)
            serializer = FlowerListSerializer(flowers, many=True)
            return APIResponse.success(data=serializer.data, message="获取热门鲜花成功")
        except Exception as e:
            return APIResponse.error(message=f"获取热门鲜花失败: {str(e)}")

    @action(detail=False, methods=['get'])
    def featured(self, request):
        """获取推荐鲜花"""
        try:
            limit = int(request.query_params.get('limit', 10))
            flowers = FlowerSearchService.get_featured_flowers(limit)
            serializer = FlowerListSerializer(flowers, many=True)
            return APIResponse.success(data=serializer.data, message="获取推荐鲜花成功")
        except Exception as e:
            return APIResponse.error(message=f"获取推荐鲜花失败: {str(e)}")

    @action(detail=False, methods=['post'])
    def upload_image(self, request):
        """上传图片"""
        try:
            serializer = ImageUploadSerializer(data=request.data)
            if serializer.is_valid():
                image_file = serializer.validated_data['image']
                image_url = ImageUploadService.upload_image(image_file)
                return APIResponse.success(
                    data={'image_url': image_url},
                    message="图片上传成功"
                )
            return APIResponse.error(message="数据验证失败", data=serializer.errors)
        except ValidationError as e:
            return APIResponse.error(message=str(e))
        except Exception as e:
            return APIResponse.error(message=f"图片上传失败: {str(e)}")

    @action(detail=False, methods=['post'])
    def batch_upload_images(self, request):
        """批量上传鲜花图片到OSS"""
        try:
            # 鲜花图片URL映射
            flower_image_urls = {
                "红玫瑰花束": "https://images.unsplash.com/photo-1518895949257-7621c3c786d7?w=800&h=600&fit=crop",
                "粉玫瑰花束": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
                "白玫瑰花束": "https://images.unsplash.com/photo-1582794543139-8ac9cb0f7b11?w=800&h=600&fit=crop",
                "红康乃馨花束": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
                "粉康乃馨花束": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
                "白百合花束": "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
                "粉百合花束": "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
                "向日葵花束": "https://images.unsplash.com/photo-1470509037663-253afd7f0f51?w=800&h=600&fit=crop",
                "红郁金香花束": "https://images.unsplash.com/photo-1520637836862-4d197d17c93a?w=800&h=600&fit=crop",
                "粉郁金香花束": "https://images.unsplash.com/photo-1584464491033-06628f3a6b7b?w=800&h=600&fit=crop",
                "满天星花束": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop"
            }
            
            results = []
            success_count = 0
            error_count = 0
            
            for flower_name, image_url in flower_image_urls.items():
                try:
                    # 查找对应的鲜花
                    flower = Flower.objects.filter(name=flower_name).first()
                    if not flower:
                        results.append({
                            'flower_name': flower_name,
                            'status': 'error',
                            'message': '未找到对应的鲜花商品'
                        })
                        error_count += 1
                        continue
                    
                    # 检查是否已有主图
                    existing_image = flower.images.filter(is_main=True).first()
                    force = request.data.get('force', False)
                    
                    if existing_image and not force:
                        results.append({
                            'flower_name': flower_name,
                            'status': 'skipped',
                            'message': '已有主图，跳过上传'
                        })
                        continue
                    
                    # 从URL上传图片
                    filename = f"{flower_name}.jpg"
                    oss_url = ImageUploadService.upload_image_from_url(image_url, filename)
                    
                    # 删除旧图片
                    if existing_image:
                        ImageUploadService.delete_image(existing_image.image_url)
                        existing_image.delete()
                    
                    # 创建新的图片记录
                    from .models import FlowerImage
                    FlowerImage.objects.create(
                        flower=flower,
                        image_url=oss_url,
                        is_main=True,
                        sort_order=0
                    )
                    
                    results.append({
                        'flower_name': flower_name,
                        'status': 'success',
                        'image_url': oss_url,
                        'message': '上传成功'
                    })
                    success_count += 1
                    
                except Exception as e:
                    results.append({
                        'flower_name': flower_name,
                        'status': 'error',
                        'message': str(e)
                    })
                    error_count += 1
            
            return APIResponse.success(
                data={
                    'results': results,
                    'summary': {
                        'total': len(flower_image_urls),
                        'success': success_count,
                        'error': error_count
                    }
                },
                message=f"批量上传完成，成功: {success_count}, 失败: {error_count}"
            )
            
        except Exception as e:
            return APIResponse.error(message=f"批量上传失败: {str(e)}")
